import socket
from lib.BaseExploit import BaseExploit


class Exploit(BaseExploit):
    def __init__(self):
        super(Exploit, self).__init__()
        self.update_info({
            "name": "redis unauthorized",
            "description": "redis unauthorized",
            "author": ["unknown"],
            "references": [
                "https://www.freebuf.com/column/158065.html",
            ],
            "disclosure_date": "2019-02-28",
            "service_name": "redis",
            "service_version": "*",
        })
        self.register_tcp_target(port_value=6379)

    def check(self):
        host = self.options.get_option("HOST")
        port = int(self.options.get_option("PORT"))
        timeout = int(self.options.get_option("TIMEOUT"))
        
        try:
            socket.setdefaulttimeout(timeout)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((host, port))
            s.send(bytes("INFO\r\n", encoding="utf-8"))
            result = s.recv(1024)
            if bytes("redis_version", encoding="utf-8") in result:
                self.results.success(
                    data={
                        "host": host,
                        "port": port,
                    },
                    message="Host {host}:{port} exists redis unauthorized vulnerability".format(host=host, port=port)
                )
            else:
                self.results.failure(
                    error_message="Host {host}:{port} does not exists redis unauthorized vulnerability".format(
                        host=host,
                        port=port
                    )
                )
        except Exception as e:
            self.results.failure(error_message="Host {host}:{port}: {error}".format(host=host, port=port, error=e))
        return self.results

    def exploit(self):
        return self.check()
